<?php

namespace App\Services\Api;

/**
 * X计划订单相关接口类封装
 * @package App\Services\Api
 */
class XplanOrderService
{
    const ERROR_NO_ORDER = 10001;
    const ERROR_NO_MOBILE = 10002;
    const ERROR_OUT_TIME = 10003;
    const ERROR_NO_CUSTOMER = 10004;
    const ERROR_MISS_PARAMS = 20001;

    protected $errorType;

    /**
     * 构造函数
     */
    public function __construct()
    {
        $this->errorType = [
            self::ERROR_NO_ORDER => '订单号不存在',
            self::ERROR_NO_MOBILE => '下定手机号码匹配错误',
            self::ERROR_OUT_TIME => '查询超时（服务异常）',
            self::ERROR_NO_CUSTOMER => '客人不存在',
            self::ERROR_MISS_PARAMS => '缺少必要的参数',
        ];
    }

    /**
     * 通过客户的customerId查询订单
     * private String customerName;// 主单号名称：获取客户名称+定制家居，比如：张小姐的定制家居
     * private String customerId;//客人ID
     * private String orderNum;// 主单号
     * private String customerStatus;//客人状态
     * private String createdCus;//创建客户时间
     * private String createOrdered;//待测量时间
     * private String measured;//测量完成时间
     * private String drawed;//出图完成时间
     * private String commitDrawed;//确图完成时间
     * private String commitOrdered;//已下单时间
     * private String checkDrawed;//已审图时间
     * private String issuedOrder;//已排单时间
     * private String produced;//已发货时间
     * private String executed;//已安装时间
     * private String cancelOrder;//已退单时间
     * private String shopId;//订单所属门店
     * private String orderSquare;//订单总方量
     * private String installFlag;//是否需要预约安装 Y/N
     * private String dealerName;//所属经销商
     * private String guideName;//导购
     * private String guidePhone;//导购电话
     * private String designerName;//设计师
     * private String designerPhone;//设计师电
     */
    public function getOrderById($customerId)
    {
        $param = ['customerId' => $customerId,];
        try {
            $orderQueryUrl = config('url.order_query');
            $client = new \SoapClient($orderQueryUrl);
            $response = $client->__soapCall('getCustOptyListByCustId', array(
                $param
            ));
            if (!empty($response->getCustOptyListByCustIdReturn)) {
                // 操作成功
                $json = json_decode($response->getCustOptyListByCustIdReturn, true);
                if (empty($json)) {
                    return false;
                }
                return $json;
            } else {
                \Log::error('调用订单查询接口返回异常', ['response' => $response]);
                throw new \Exception('调用订单查询接口返回异常');
            }
        } catch (\Exception $e) {
            \Log::error('调用订单查询绑定接口异常', ['errms' => $e->getMessage(), 'param' => $param]);
            throw new \Exception('调用订单查询绑定接口异常');
        }
    }

    /**
     * 保客绑定接口【旧系统发现没有地方用到这个方法，不知道做什么用的】
     * @param $custPhone 用户手机号码
     * @param $custOrderNumber 用户订单号
     * @return bool
     */
    public function getBindUser($custPhone, $custOrderNumber)
    {
        $param = [
            'custPhone' => $custPhone,
            'orderNum' => $custOrderNumber,
        ];
        try {
            $orderBindUrl = config('url.order_bind');
            $client = new \SoapClient($orderBindUrl);
            $response = $client->__soapCall('getCustomerID', [
                $param
            ]);
            if (!empty($response->getCustomerIDReturn)) {
                // 操作成功
                if (isset($this->errorType[$response->getCustomerIDReturn])) {
                    throw new \Exception($this->errorArr[$response->getCustomerIDReturn]);
                }
                return $response->getCustomerIDReturn;
            } else {
                \Log::error('调用用户绑定接口返回异常', ['response' => $response]);
                throw new \Exception('绑定失败，原因未知');
            }
        } catch (\Exception $e) {
            \Log::error('调用用户绑定接口异常', ['errms' => $e->getMessage(), 'param' => $param]);
            throw new \Exception('系统升级，暂时无法绑定');
        }
        return false;
    }

    /**
     * 通过手机号查询用户key
     * @param $custPhone
     * @return bool
     */
    public function getCustomerIdByPhone($custPhone)
    {
        $param = ['custPhone' => $custPhone,];
        try {
            $orderBindUrl = config('url.order_phone');
            $client = new \SoapClient($orderBindUrl);
            $response = $client->__soapCall('getCustomerIDByPhone', [
                $param
            ]);
            if (!empty($response->getCustomerIDByPhoneReturn)) {
                // 操作成功
                if (isset($this->errorType[$response->getCustomerIDByPhoneReturn])) {
                    throw new \Exception($this->errorType[$response->getCustomerIDByPhoneReturn]);
                }
                return $response->getCustomerIDByPhoneReturn;
            } else {
                \Log::error('手机号查询订单接口返回异常', ['response' => $response]);
                throw new \Exception('绑定失败，原因未知');
            }
        } catch (\Exception $e) {
            \Log::error('调用手机查询订单接口异常', ['errmsg' => $e->getMessage(), 'param' => $param]);
            throw new \Exception('系统升级，暂时无法查询订单');
        }
    }

    /**
     * 通过手机号直接查询用户的订单数据（新接口）
     * 接口文档 http://192.168.168.144:8091/web/#/8?page_id=219
     * @param $phone
     * @return array
     */
    public function getOrderByPhone($phone)
    {
        try {
            $now = time();
            $token = md5($phone . $now . 'sogalcrm15#');
            $param = ['phone' => $phone, 'timestamp' => $now, 'token' => $token];

            $res = (new \GuzzleHttp\Client())->request('GET', config('url.order_phone_new'),['query'=>$param]);

            if ($res->getStatusCode() == 200){

                $result = json_decode($res->getBody(),true);

                if ($result['success']){
                    return $result['data'] ?? [];
                }else{
                    throw new \Exception($result['message'] ?? '接口返回异常');
                }
            }
            \Log::error('调用订单查询绑定接口异常', ['errms' => $param]);
            throw new \Exception('调用订单查询绑定接口异常');

        } catch (\Exception $e) {
            \Log::error('调用订单查询绑定接口异常', ['errms' => $e->getMessage()]);
            throw new \Exception($e->getMessage());
        }

    }


}